package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ExhaustGasWarningConfigMapper;
import com.bf.electroplating.pojo.entity.ExhaustGasWarningConfig;
import com.bf.electroplating.pojo.vo.exhaustGasWarningConfig.ExhaustGasWarningConfigAddDTO;
import com.bf.electroplating.pojo.vo.exhaustGasWarningConfig.ExhaustGasWarningConfigQueryDTO;
import com.bf.electroplating.pojo.vo.exhaustGasWarningConfig.ExhaustGasWarningConfigUpdateDTO;
import com.bf.electroplating.pojo.vo.exhaustGasWarningConfig.ExhaustGasWarningConfigVO;
import com.bf.electroplating.service.IExhaustGasWarningConfigService;
// import com.bf.electroplating.util.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 废气处理设施监控预警设置服务实现类
 */
@Slf4j
@Service
public class ExhaustGasWarningConfigServiceImpl extends ServiceImpl<ExhaustGasWarningConfigMapper, ExhaustGasWarningConfig> 
        implements IExhaustGasWarningConfigService {

    @Override
    public Page<ExhaustGasWarningConfigVO> pageList(ExhaustGasWarningConfigQueryDTO queryDTO) {
        log.info("分页查询废气预警配置，查询条件：{}", queryDTO);
        
        Page<ExhaustGasWarningConfig> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        LambdaQueryWrapper<ExhaustGasWarningConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExhaustGasWarningConfig::getDelFlag, "0")
                .eq(StringUtils.hasText(queryDTO.getCompanyId()), ExhaustGasWarningConfig::getCompanyId, queryDTO.getCompanyId())
                .like(StringUtils.hasText(queryDTO.getCompanyName()), ExhaustGasWarningConfig::getCompanyName, queryDTO.getCompanyName())
                .like(StringUtils.hasText(queryDTO.getParkId()), ExhaustGasWarningConfig::getParkId, queryDTO.getParkId())
                .like(StringUtils.hasText(queryDTO.getParkName()), ExhaustGasWarningConfig::getParkName, queryDTO.getParkName())
                .like(StringUtils.hasText(queryDTO.getDeviceId()), ExhaustGasWarningConfig::getDeviceId, queryDTO.getDeviceId())
                .like(StringUtils.hasText(queryDTO.getDeviceName()), ExhaustGasWarningConfig::getDeviceName, queryDTO.getDeviceName())
                .like(StringUtils.hasText(queryDTO.getDeviceCode()), ExhaustGasWarningConfig::getDeviceCode, queryDTO.getDeviceCode())
                .like(StringUtils.hasText(queryDTO.getMonitoringFactor()), ExhaustGasWarningConfig::getMonitoringFactor, queryDTO.getMonitoringFactor())
                .like(StringUtils.hasText(queryDTO.getMonitoringFactorCode()), ExhaustGasWarningConfig::getMonitoringFactorCode, queryDTO.getMonitoringFactorCode())
                .eq(StringUtils.hasText(queryDTO.getWarningLevel()), ExhaustGasWarningConfig::getWarningLevel, queryDTO.getWarningLevel())
                .eq(StringUtils.hasText(queryDTO.getIsEnabled()), ExhaustGasWarningConfig::getIsEnabled, queryDTO.getIsEnabled())
                .like(StringUtils.hasText(queryDTO.getDataSource()), ExhaustGasWarningConfig::getDataSource, queryDTO.getDataSource())
                .orderByDesc(ExhaustGasWarningConfig::getCreateTime);
        
        Page<ExhaustGasWarningConfig> configPage = this.page(page, wrapper);
        
        // 转换为VO
        Page<ExhaustGasWarningConfigVO> voPage = new Page<>();
        BeanUtils.copyProperties(configPage, voPage, "records");
        
        List<ExhaustGasWarningConfigVO> voList = configPage.getRecords().stream()
                .map(this::convertToVO)
                .toList();
        
        voPage.setRecords(voList);
        
        log.info("分页查询废气预警配置完成，共{}条记录", voList.size());
        return voPage;
    }

    @Override
    public ExhaustGasWarningConfigVO getDetail(String id) {
        log.info("获取废气预警配置详情，ID：{}", id);
        
        ExhaustGasWarningConfig config = this.getById(id);
        if (config == null) {
            log.warn("废气预警配置不存在，ID：{}", id);
            return null;
        }
        
        return convertToVO(config);
    }

    @Override
    public Boolean addConfig(ExhaustGasWarningConfigAddDTO addDTO) {
        log.info("新增废气预警配置，数据：{}", addDTO);
        
        try {
            ExhaustGasWarningConfig config = new ExhaustGasWarningConfig();
            BeanUtils.copyProperties(addDTO, config);
            
            config.setId(UUID.randomUUID().toString().replace("-", ""));
            config.setCreateBy("系统管理员");
            config.setCreateTime(LocalDateTime.now());
            config.setUpdateBy("系统管理员");
            config.setUpdateTime(LocalDateTime.now());
            config.setDelFlag("0");
            
            boolean result = this.save(config);
            log.info("新增废气预警配置{}，ID：{}", result ? "成功" : "失败", config.getId());
            return result;
            
        } catch (Exception e) {
            log.error("新增废气预警配置失败", e);
            return false;
        }
    }

    @Override
    public Boolean updateConfig(ExhaustGasWarningConfigUpdateDTO updateDTO) {
        log.info("更新废气预警配置，数据：{}", updateDTO);
        
        try {
            ExhaustGasWarningConfig config = this.getById(updateDTO.getId());
            if (config == null) {
                log.warn("废气预警配置不存在，ID：{}", updateDTO.getId());
                return false;
            }
            
            BeanUtils.copyProperties(updateDTO, config, "id", "createBy", "createTime", "delFlag");
            config.setUpdateBy("系统管理员");
            config.setUpdateTime(LocalDateTime.now());
            
            boolean result = this.updateById(config);
            log.info("更新废气预警配置{}，ID：{}", result ? "成功" : "失败", config.getId());
            return result;
            
        } catch (Exception e) {
            log.error("更新废气预警配置失败", e);
            return false;
        }
    }

    @Override
    public Boolean deleteConfig(String id) {
        log.info("删除废气预警配置，ID：{}", id);
        
        try {
            ExhaustGasWarningConfig config = this.getById(id);
            if (config == null) {
                log.warn("废气预警配置不存在，ID：{}", id);
                return false;
            }
            
            config.setDelFlag("1");
            config.setUpdateBy("系统管理员");
            config.setUpdateTime(LocalDateTime.now());
            
            boolean result = this.updateById(config);
            log.info("删除废气预警配置{}，ID：{}", result ? "成功" : "失败", id);
            return result;
            
        } catch (Exception e) {
            log.error("删除废气预警配置失败", e);
            return false;
        }
    }

    @Override
    public Boolean batchDeleteConfig(String[] ids) {
        log.info("批量删除废气预警配置，IDs：{}", Arrays.toString(ids));
        
        try {
            List<ExhaustGasWarningConfig> configList = this.listByIds(Arrays.asList(ids));
            if (configList.isEmpty()) {
                log.warn("未找到要删除的废气预警配置");
                return false;
            }
            
            configList.forEach(config -> {
                config.setDelFlag("1");
                config.setUpdateBy("系统管理员");
                config.setUpdateTime(LocalDateTime.now());
            });
            
            boolean result = this.updateBatchById(configList);
            log.info("批量删除废气预警配置{}，共{}条", result ? "成功" : "失败", configList.size());
            return result;
            
        } catch (Exception e) {
            log.error("批量删除废气预警配置失败", e);
            return false;
        }
    }

    @Override
    public Boolean updateEnabledStatus(String id, String isEnabled) {
        log.info("更新废气预警配置启用状态，ID：{}，状态：{}", id, isEnabled);
        
        try {
            ExhaustGasWarningConfig config = this.getById(id);
            if (config == null) {
                log.warn("废气预警配置不存在，ID：{}", id);
                return false;
            }
            
            config.setIsEnabled(isEnabled);
            config.setUpdateBy("系统管理员");
            config.setUpdateTime(LocalDateTime.now());
            
            boolean result = this.updateById(config);
            log.info("更新废气预警配置启用状态{}，ID：{}，状态：{}", result ? "成功" : "失败", id, isEnabled);
            return result;
            
        } catch (Exception e) {
            log.error("更新废气预警配置启用状态失败", e);
            return false;
        }
    }

    /**
     * 转换为VO
     */
    private ExhaustGasWarningConfigVO convertToVO(ExhaustGasWarningConfig config) {
        ExhaustGasWarningConfigVO vo = new ExhaustGasWarningConfigVO();
        BeanUtils.copyProperties(config, vo);
        
        // 设置预警级别名称
        if ("1".equals(config.getWarningLevel())) {
            vo.setWarningLevelName("一级预警");
        } else if ("2".equals(config.getWarningLevel())) {
            vo.setWarningLevelName("二级预警");
        } else if ("3".equals(config.getWarningLevel())) {
            vo.setWarningLevelName("三级预警");
        }
        
        // 设置启用状态名称
        if ("1".equals(config.getIsEnabled())) {
            vo.setIsEnabledName("启用");
        } else if ("0".equals(config.getIsEnabled())) {
            vo.setIsEnabledName("停用");
        }
        
        return vo;
    }
}
